package com.onlineshop.controller.admin;

import com.onlineshop.dao.ProductDao;
import com.onlineshop.entity.Product;
import com.onlineshop.util.FileUploadUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

@WebServlet("/admin/products/edit")
public class EditProductServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/admin/products");
            return;
        }

        try {
            int productId = Integer.parseInt(idStr);
            Product product = productDao.getProductById(productId);
            if (product != null) {
                request.setAttribute("product", product);
                request.getRequestDispatcher("/admin/edit_product.jsp").forward(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/admin/products?error=商品不存在");
            }
        } catch (NumberFormatException e) {
            response.sendRedirect(request.getContextPath() + "/admin/products?error=无效的商品ID");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求字符编码
        request.setCharacterEncoding("UTF-8");
        Map<String, String> formFields = FileUploadUtil.parseRequest(request);

        String idStr = formFields.get("id");
        String name = formFields.get("name");
        String priceStr = formFields.get("price");
        String stockStr = formFields.get("stock");
        String description = formFields.get("description");
        String image = formFields.get("image"); // 新上传的文件名
        String originalImage = formFields.get("originalImage"); // 原始图片名

        // 如果没有上传新图片，保留原始图片
        if (image == null || image.isEmpty()) {
            image = originalImage;
        }

        if (idStr == null || idStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/admin/products?error=无效请求");
            return;
        }

        try {
            int productId = Integer.parseInt(idStr);
            BigDecimal price = new BigDecimal(priceStr);
            int stock = Integer.parseInt(stockStr);

            Product product = new Product();
            product.setProductId(productId);
            product.setName(name);
            product.setPrice(price);
            product.setStock(stock);
            product.setDescription(description);
            product.setImage(image);

            boolean success = productDao.updateProduct(product);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/admin/products?success=更新商品成功");
            } else {
                response.sendRedirect(request.getContextPath() + "/admin/products/edit?id=" + productId + "&error=更新商品失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/admin/products/edit?id=" + request.getParameter("id") + "&error=文件上传失败" + e.getMessage());
        }
    }
}